'''
1、
'''
import time

import pygame,sys
from pygame.locals import *
from random import choice

import enemy,wangzi,supply

pygame.init()
pygame.mixer.init()
pygame.mouse.set_visible(False)  # 鼠标消失不见
bg_size = width, height = 700, 900


screen = pygame.display.set_mode(bg_size)
pygame.display.set_caption("躲避汉堡🍔")

background = pygame.image.load('images/terr.jpeg').convert_alpha()
background2 = pygame.image.load('images/sky.jpg').convert_alpha()

start_image = pygame.image.load('images/gamestart.png').convert_alpha()
start_image = pygame.transform.scale(start_image,(51,12))
ice_image = pygame.image.load('images/ice.png').convert_alpha()
ice_image = pygame.transform.scale(ice_image,(50,50))
huacai_image = pygame.image.load('images/xilanhua.png').convert_alpha()
huacai_image = pygame.transform.scale(huacai_image,(50,50))

dunpai_image = pygame.image.load('images/dunpai.png').convert_alpha()
dunpai_image = pygame.transform.scale(dunpai_image,(100,100))

# 游戏音乐
pygame.mixer.music.load('sounds/music1.mp3')
pygame.mixer.music.set_volume(0.5)
gameOverSound = pygame.mixer.Sound('sounds/gameover.mp3')
me_down_sound = pygame.mixer.Sound('sounds/dead.mp3')
#me_down_sound.set_volume(0.5)
upgrade_sound = pygame.mixer.Sound('sounds/levelup.mp3')
#upgrade_sound.set_volume(0.5)
ice_sound = pygame.mixer.Sound('sounds/ice.mp3')
start_game_sound = pygame.mixer.Sound('sounds/start_game.mp3')
huacai_sound = pygame.mixer.Sound('sounds/huacai.mp3')
levelup_sound = pygame.mixer.Sound('sounds/levelup.mp3')
hudun_sound = pygame.mixer.Sound('sounds/hudun.mp3')


WINDOWWIDTH = 1024 # 窗口宽度
WINDOWHEIGHT = 768 # 窗口高度
TEXTCOLOR = (0,0,0)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)

# 设置字体声音图片
font = pygame.font.Font('fengheguai.otf', 48)  # 48 字体大小

# 文本渲染函数
def drawText(text, font, surface, x, y,textcolor):
    textobj = font.render(text, 1, textcolor)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)

# 终止和暂停游戏
def terminate():
    pygame.quit()
    sys.exit()

def inc_speed(target, inc):
    for each in target:
        each.speed +=1

def de_speed(target,inc):
    for each in target:
        each.speed -= 5

# 循环 开始游戏
def waitForPlayerToPressKey():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:  # Pressing ESC quits.
                    terminate()
                return


# 敌人添加函数
def add_small_enemies(group1, group2, num):
    for i in range(num):
        e1 = enemy.Hanbao(bg_size)
        group1.add(e1)
        group2.add(e1)


def main():

    pygame.mixer.music.play(-1)
    # 分数
    score = 0
    score_font = pygame.font.Font('LanaPixel.ttf', 36)

    # 得分字体颜色
    score_font_color = WHITE

    # 分数权重
    timeScore = 1

    # 生成player
    me = wangzi.Wangzi(bg_size)

    # 难度控制
    level = 1

    # 绘制敌人
    enemies = pygame.sprite.Group()

    # 生成小敌机
    small_enemies = pygame.sprite.Group()
    add_small_enemies(small_enemies, enemies, 50)




    # 延迟变量
    delay = 100
    # 中弹图片索引
    e1_destory_index = 0
    e2_destory_index = 0
    e3_destory_index = 0
    my_destory_index = 0

    # 补给包
    ices = pygame.sprite.Group()
    cais = pygame.sprite.Group()

    ice_supply = supply.Ice_Supply(bg_size)
    cai_supply = supply.Cai_Supply(bg_size)
    berry_supply = supply.Berry_Supply(bg_size)





    # 生命数量
    life_image = pygame.transform.scale(pygame.image.load('images/dxx.png').convert_alpha(),(78,84))
    life_rect = life_image.get_rect()
    life_num = 3

    # record 变量 用于限制重复打开记录文件
    recorded = False

    # 双倍分数
    is_double_score = False

    # 开始游戏
    screen.blit(background2,(0,0))
    drawText('躲避汉堡', font, screen, (WINDOWWIDTH / 9), (WINDOWHEIGHT / 3),WHITE)
    drawText('按任意键开始游戏', font, screen, (WINDOWWIDTH / 9) , (WINDOWHEIGHT / 3) + 50,WHITE)
    pygame.display.update()
    clock = pygame.time.Clock()

    # 游戏开始页面
    waitForPlayerToPressKey()
    # 补给发放时间间隔
    SUPPLY_TIME_GAP = 10 * 1000


    # 无敌状态接触定时器
    INVINCIBLE_TIME = USEREVENT
    # 花菜双倍
    CAI_TIME = USEREVENT + 1

    SUPPLY_TIME = USEREVENT +2
    pygame.time.set_timer(SUPPLY_TIME, SUPPLY_TIME_GAP)

    # 雪花补给
    ICE_TIME = USEREVENT + 3
    BERRY_TIME = USEREVENT +4

    pygame.time.set_timer(ICE_TIME,0)
    # 获取历史最高分
    record_score = 0
    with open('record.txt','r') as f:
        record_score = str(f.read())
        f.close()


    running = True
    while running:
        # 是否双倍经验
        if is_double_score:
            score += (timeScore*2)
        else:
            score += timeScore


        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    pygame.quit()
                    sys.exit()
            elif event.type == MOUSEMOTION:
                # If the mouse moves, move the player where to the cursor.
                me.rect.centerx = event.pos[0]
                me.rect.centery = event.pos[1]
            elif event.type == INVINCIBLE_TIME:
                me.invincible = False
                pygame.time.set_timer(INVINCIBLE_TIME, 0)
            elif event.type == SUPPLY_TIME:
                ice_supply.reset()
                cai_supply.reset()
                berry_supply.reset()
                # # huacai_sound.play()
                # if choice([True, False]):
                #     ice_supply.reset()
                # else:
                #     cai_supply.reset()
            elif event.type == CAI_TIME:
                is_double_score = False
                score_font_color = WHITE
                pygame.time.set_timer(CAI_TIME, 0)
            elif event.type == ICE_TIME:
                for each in enemies:
                    each.speed += 3
                pygame.time.set_timer(ICE_TIME,0)



                # 根据得分 增加难度
        if level == 1 and score > 1000:
            timeScore+=1
            level = 2
            upgrade_sound.play()
            # 增加3个小型敌机 2个中型敌机 1个大型敌机
            add_small_enemies(small_enemies, enemies, 10)
            # 提升小型敌机速度
            inc_speed(small_enemies, 1)
            # 间隔减少
            SUPPLY_TIME_GAP = 8*1000
        elif level == 2 and score > 10000:
            timeScore+=2
            level = 3
            upgrade_sound.play()
            # 增加3个小型敌机 2个中型敌机 1个大型敌机
            add_small_enemies(small_enemies, enemies, 10)
            # 提升小型敌机速度
            inc_speed(small_enemies, 1)
            # 间隔减少
            SUPPLY_TIME_GAP =  6* 1000
        elif level == 3 and score > 50000:
            timeScore+=5
            level = 4
            upgrade_sound.play()
            # 增加3个小型敌机 2个中型敌机 1个大型敌机
            add_small_enemies(small_enemies, enemies, 10)
            # 提升小型敌机速度
            inc_speed(small_enemies, 1)
            # 间隔减少
            SUPPLY_TIME_GAP = 4 * 1000
        elif level == 4 and score > 100000:
            timeScore+=10
            level = 5
            upgrade_sound.play()
            # 增加3个小型敌机 2个中型敌机 1个大型敌机
            add_small_enemies(small_enemies, enemies, 10)
            # 提升小型敌机速度
            inc_speed(small_enemies, 1)
            # 间隔减少
            SUPPLY_TIME_GAP = 2 * 1000
        elif level == 5 and score > 500000:
            timeScore+=20
            level = 6
            upgrade_sound.play()
            # 增加3个小型敌机 2个中型敌机 1个大型敌机
            add_small_enemies(small_enemies, enemies, 5)
            # 提升小型敌机速度
            inc_speed(small_enemies, 1)
            # 间隔减少
            SUPPLY_TIME_GAP = 1 * 1000

        screen.blit(background2, (0, 0))

        if life_num :
            key_pressed = pygame.key.get_pressed()
            if key_pressed[K_w] or key_pressed[K_UP]:
                me.moveUp()
            if key_pressed[K_s] or key_pressed[K_DOWN]:
                me.moveDown()
            if key_pressed[K_a] or key_pressed[K_LEFT]:
                me.moveLeft()
            if key_pressed[K_d] or key_pressed[K_RIGHT]:
                me.moveRight()

            # 冰雪花碰撞检测
            if ice_supply.active:
                ice_supply.move()
                screen.blit(ice_supply.image, ice_supply.rect)
                if pygame.sprite.collide_mask(ice_supply, me):
                    ice_sound.play()
                    # 所有汉堡下降速度减少

                    # if bomb_num < 3:
                    #     bomb_num += 1
                    ice_supply.active = False
                    pygame.time.set_timer(ICE_TIME,2*1000)
                    for each in enemies:
                        each.speed -= 3

            # 花菜碰撞检测  双倍 立即获得多少分
            if cai_supply.active:
                cai_supply.move()
                screen.blit(cai_supply.image, cai_supply.rect)
                if pygame.sprite.collide_mask(cai_supply, me):
                    huacai_sound.play()
                    score += 2000
                    is_double_score = True
                    pygame.time.set_timer(CAI_TIME, 5 * 1000)
                    # 分数红色表示双倍中
                    score_font_color = RED
                    # 花菜销毁
                    cai_supply.active = False
            # 草莓碰撞检测 添加护盾和分数
            if berry_supply.active:
                berry_supply.move()
                screen.blit(berry_supply.image, berry_supply.rect)
                if pygame.sprite.collide_mask(berry_supply, me):
                    # hudun_sound.play()
                    huacai_sound.play()
                    score += 2000
                    pygame.time.set_timer(INVINCIBLE_TIME, 5 * 1000)
                    # 分数红色表示双倍中
                    score_font_color = RED
                    # 草莓销毁
                    berry_supply.active = False
                    # 无敌
                    me.invincible = True


            # 检测是否被撞
            enemies_down = pygame.sprite.spritecollide(me, enemies, False, pygame.sprite.collide_mask)
            if enemies_down and not me.invincible:
                me.active = False
                # 同时删除被撞敌人
                for e in enemies_down:
                    e.active = False

            # 汉堡
            for each in small_enemies:
                if each.active:
                    each.move()
                    screen.blit(each.image, each.rect)
                else:
                    # 毁灭
                    if not (delay % 3):
                        if e1_destory_index == 0:
                            #enemy1_down_sound.play()
                            pass
                        #screen.blit(each.destroy_images[e1_destory_index], each.rect)
                        e1_destory_index = (e1_destory_index + 1) % 4
                        if e1_destory_index == 0:
                            #score += 1000
                            each.reset()

            # 绘制生命数量
            if life_num:
                for i in range(life_num):
                    screen.blit(life_image,
                                (width - 10 - (i + 1) * life_rect.width, height - 10 - life_rect.height))

            # 绘制me
            if me.active:
                # if switch_image:
                #     screen.blit(me.image1, me.rect)
                # else:
                #     screen.blit(me.image2, me.rect)
                screen.blit(me.image1,me.rect)
            else:
                # 毁灭
                if not (delay % 3):
                    if my_destory_index == 0:
                        me_down_sound.play()
                    # #screen.blit(me.destroy_images[my_destory_index], me.rect)
                    # my_destory_index = (my_destory_index + 1) % 4
                    # if my_destory_index == 0:
                    if life_num !=0:
                        pygame.time.set_timer(INVINCIBLE_TIME, 3*1000)
                        life_num -= 1
                        me.reset()

            if me.invincible:
                screen.blit(dunpai_image, (me.rect.left-25,me.rect.top-20))



        elif life_num == 0:
            # 游戏结束音效
            gameOverSound.play(1)
            pygame.time.wait(1*1000)
            # 背景音乐停止
            pygame.mixer.music.stop()
            # 停止全部音效
            pygame.mixer.stop()
            # 分数为0
            timeScore = 0

            # 补给定时器
            #pygame.time.set_timer(SUPPLY_TIME, 0)
            if not recorded:
                recorded = True
                # 读取历史最高得分记录文件
                if score > int(record_score):
                    with open('record.txt', 'w') as f:
                        f.write(str(score))

            drawText('GAME OVER', font, screen, (WINDOWWIDTH / 7), (WINDOWHEIGHT / 3),WHITE)
            drawText('按任意键继续', font, screen, (WINDOWWIDTH / 7) , (WINDOWHEIGHT / 3) + 50,WHITE)
            drawText('您的分数是: '+str(score ), font, screen, (WINDOWWIDTH / 7) , (WINDOWHEIGHT / 3) + 100, WHITE)
            drawText('历史最高分是: ' + str(record_score), font, screen, (WINDOWWIDTH / 7) , (WINDOWHEIGHT / 3) + 150, WHITE)
            pygame.display.update()

            while True:
                for event in pygame.event.get():
                    if event.type == QUIT:
                        terminate()
                    if event.type == KEYDOWN:
                        if event.key == K_ESCAPE:  # Pressing ESC quits.
                            terminate()
                        else:
                            main()

        # 绘制分数
        score_text = score_font.render("Score : %s" % str(score), True, score_font_color)
        screen.blit(score_text, (10, 5))

        # 绘制当前等级
        level_text = score_font.render("Level : %s" % str(score), True, WHITE)
        drawText("Level : %s" % str(level), score_font, screen, 580,5,WHITE)
        # 延迟参数
        if not (delay % 5):
            # switch_image = not switch_image
            pass
        delay -= 1
        if not delay:
            delay = 100
        pygame.display.flip()
        clock.tick(60)

if __name__ == '__main__':
    main()